import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  Button,
  FormControl,
  FormLabel,
  Input,
  VStack
} from "@chakra-ui/react"

export default function CreateUpdate(props) {
  const { isOpen, onClose, initialState, onSubmitState } = props
  const cancelRef = React.useRef()
  const [ id, setId ] = useState('')
  const [ webName, setWebName ] = useState('')
  const [ webSite, setWebSite ] = useState('')

  useEffect(() => {
    const { detail } = initialState
    if (detail) {
      setId(detail.id)
      setWebName(detail.title)
      setWebSite(detail.link)
    } else {
      setWebName('')
      setWebSite('')
    }
  }, [isOpen])

  const onSubmit = () => {
    if (isReady) {
      onSubmitState({
        id,
        webName,
        webSite,
      })
    }
  }

  const isReady = useMemo(() => {
    return Boolean(webName && webSite)
  }, [webName, webSite])

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>{initialState.title}</ModalHeader>
        <ModalBody>
          <VStack spacing={2}>
            <FormControl id="web-name" >
              <FormLabel>名称</FormLabel>
              <Input placeholder="名称" value={webName}  onChange={({ target }) => setWebName(target.value)}/>
            </FormControl>
            <FormControl id="web-site">
              <FormLabel>网址</FormLabel>
              <Input placeholder="网址"  value={webSite} onChange={({ target }) => setWebSite(target.value)}/>
            </FormControl>
          </VStack>
        </ModalBody>

        <ModalFooter>
          <Button ref={cancelRef} size="sm" variant="ghost" onClick={onClose}>
            取消
          </Button>
          <Button ml={3} onClick={onSubmit} size="sm">
            完成
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  )
}